package com.xlf.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 使用AOP技术，输出Controller层的日志
 */

@Aspect
@Component
@Slf4j
public class LogAspect {

    /**
     * 切点表达式，根据表达式定义的路径拦截方法
     * 现在拦截的是控制层的方法
     */
    @Pointcut("execution(* com.xlf.controller.*..*(..))")
    public void log(){
    }


    /**
     * 在执行请求方法之前执行，也就是在控制层的方法执行前将该请求的路径、IP、方法（全限定名）以及参数输
     * 出到控制台，输出对象为封装好的内部类对象
     * @param joinPoint 切点对象，也就是拦截到的方法
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        log.info("Request : {}", requestLog);

    }


    /**
     * 在Controller层方法执行后输出
     */
    @After("log()")
    public void after(){
        log.info("-----------------------After Controller-----------------------");
    }


    /**
     * 在Controller层方法返回数据给前端前执行输出日志，将返回值输出到控制台
     * @param result    返回给前端的数据
     */
    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterReturn(Object result){
        log.info("Result : {}",result);
    }


    /**
     * 内部类，用来封装控制层的请求日志格式
     */
    private class RequestLog {
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
